/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { history, useModel } from 'umi';
import { useRef, useEffect } from 'react';
import type { FormInstance } from 'antd';
import { isEmpty } from 'lodash';
import { joinMiniProgramBuildTask, saveMiniProgramLicense } from '@/services/mini/aliapp';

interface FormType {
  out_door_pic: string[];
  special_license_pic: string[];
  license_pic: string[];
  license_name: string;
  license_number: string;
  license_valid_date: string;
}

export function useAliappInfoItem() {
  const formRef = useRef<FormInstance>();
  const { info, view, activeKey } = useModel('mini_aliapp');
  const { auth_appid } = info || {};
  const showPost = !info?.merchant;

  useEffect(() => {
    if (info && !isEmpty(info)) {
      const license_info: any = Array.isArray(info?.license_info) ? {} : info?.license_info;
      const params: any = {};
      if (info?.out_door_pic) {
        params.out_door_pic = [info?.out_door_pic];
      }
      if (info?.special_license_pic) {
        params.special_license_pic = info?.special_license_pic;
      }
      if (!isEmpty(license_info)) {
        if (license_info.license_pic) {
          params.license_pic = [license_info.license_pic];
        }
        if (license_info.license_name) {
          params.license_name = license_info.license_name;
        }
        if (license_info.license_number) {
          params.license_number = license_info.license_number;
        }
        if (license_info.license_valid_date) {
          params.license_valid_date = license_info.license_valid_date;
        }
      }
      formRef.current?.setFieldsValue(params);
    }
  }, [info]);

  const onFinish = async (val: FormType) => {
    const {
      out_door_pic,
      special_license_pic,
      license_pic,
      license_name,
      license_number,
      license_valid_date,
    } = val;
    const params: any = {
      auth_appid: auth_appid,
      out_door_pic: out_door_pic[0] || '',
      special_license_pic: special_license_pic || [],
    };
    if (showPost) {
      params.license_info = {
        license_pic: license_pic[0] || '',
        license_name: license_name || '',
        license_number: license_number || '',
        license_valid_date: license_valid_date || '',
      };
    }
    const status = await saveMiniProgramLicense(params);
    if (activeKey == '3' && status) {
      await joinMiniProgramBuildTask({ auth_appid: auth_appid });
    }

    if (status) {
      history.goBack();
    }
  };

  return {
    formRef,
    onFinish,
    disabled: view == '1',
  };
}
